import React, { useEffect, useLayoutEffect, useRef } from 'react'
import { fetchLogOut, fetchServerInfo, fetchUserInfo } from '@/api/global'
import { useGlobalStore } from '@/store/global'
import { useRequest } from 'ahooks'
import { recordUserOperationBehavior } from '@kedacom/userBehavior'
import jumpPage from '@/utils/jumpPage'
import shallow from 'zustand/shallow'
import { API_PROTAL_PREFIX } from '@/utils/constant'

const useInit = () => {
	/*
	url /sso/session
	*/
	const { data: userData, loading: userLoading } = useRequest(fetchUserInfo)
	/*
	url /server_info
	*/
	const { data: serverData, loading: serverLoading } = useRequest(fetchServerInfo)
	const isInit = useRef(false)

	const { setUser, setServerInfo } = useGlobalStore(
		(state) => ({
			setUser: state.setUser,
			setServerInfo: state.setServerInfo,
		}),
		shallow
	)
	/*
	useEffect/userLoading、serverLoading


	*/
	useEffect(() => {
		/*
		1. loading结束，set数据
		*/
		if (!userLoading && userData) {
			setUser(userData)
		}
		if (!serverLoading && serverData) {
			setServerInfo(serverData)
		}
		if (!userData) return
		if (isInit.current) return
		/*
		2. 设置isInit
		*/
		isInit.current = true
		/*
		根据当前地址和权限，跳转页面
		*/
		let pathname = window.location.pathname
		if (
			!userData?.enable_meeting &&
			!pathname.includes('meetingList.html') &&
			!pathname.includes('index.html') &&
			!pathname.includes('detail.html') &&
			!pathname.includes('extractCode.html') &&
			!pathname.includes('meetingSpaceShare.html') &&
			!pathname.includes('tl_passError.html') &&
			!pathname.includes('logger.html') &&
			!pathname.includes('myMeeting.html') &&
			!pathname.includes('historyMeeting.html')
		) {
			if (userData.personal_config.home_type !== 1 && userData.personal_config.home_type !== 3) {
				jumpPage('index')
				return
			}
			jumpPage('no_permission')
			return
		}
		if (!userData?.enable_cms_approval && pathname.includes('auditManage.html')) {
			jumpPage('no_permission')
			return
		}
		if (
			!userData?.is_meeting_admin &&
			(pathname.includes('sysLog.html') ||
				pathname.includes('meetingDetailLog.html') ||
				pathname.includes('sysConfig.html'))
		) {
			jumpPage('no_permission')
			return
		}
		/*
		3.  多少秒后页面不操作，退出
		*/
		recordUserOperationBehavior({
			expired_in: userData?.expired_in,
			onQuit: () => {
				fetchLogOut()
			},
		})
	}, [userLoading, serverLoading])

	/*
	useLayoutEffect/[]
	
	动态引入js文件
	*/
	useLayoutEffect(() => {
		//浏览器回退，并不会重新请求静态文件
		const script = document.createElement('script')
		script.src = `${API_PROTAL_PREFIX}/kdv/biz/bp.min.js?t=${new Date().getTime()}`
		document.getElementsByTagName('head')[0].appendChild(script)
	}, [])
}
export default useInit
